package main

import (
	"fmt"
)

func declareMap() {
	var m1 map[string]int = map[string]int{"a": 1, "b": 2}
	fmt.Println("[func|declareMap]m1=", m1, "map length: ", len(m1))
	var m2 = map[string]int{"c": 3, "d": 4}
	fmt.Println("[func|declareMap]m2=", m2, "map length: ", len(m2))
	m3 := map[string]int{"e": 5, "f": 6}
	fmt.Println("[func|declareMap]m3=", m3, "map length: ", len(m3))
	m4 := make(map[string]int, 5)
	m4["g"] = 7
	m4["h"] = 8
	fmt.Println("[func|declareMap]m4=", m4, "map length: ", len(m4))
	fmt.Println()
}

func initialMap1() {
	var m1 map[string]int = map[string]int{
		"a": 1,
		"b": 2,
	}
	fmt.Println("[func|initialMap1]m1: ", m1)
	m1["c"] = 1
	fmt.Println("[func|initialMap1]m1: ", m1)
	fmt.Println()
}

func initialMap2() {
	var m1 map[string]int
	fmt.Println("[func|initialMap2]m1: ", m1)
	fmt.Println()
	/**
	m1["c"] = 1
	fmt.Println("[func|initialMap2]m1: ", m1)

	上述代码编译报错，因为没有对map进行初始化直接对其进行写操作，报错如下：
	panic: assignment to entry in nil map
	*/
}

func visitMapKey() {
	str := "abc"
	m1 := map[rune]int{}

	for _, value := range str {
		m1[value]++
	}
	fmt.Println("[func|visitMapKey]m1=", m1)

	value1, ok := m1['z']
	fmt.Println("value1: ", value1, "ok: ", ok)

	value2, ok := m1['a']
	fmt.Println("value2: ", value2, "ok: ", ok)
	fmt.Println()
}

func deleteMap() {
	m := map[string]int{
		"a": 1,
		"b": 2,
	}
	fmt.Println("[func|deleteMap]m=", m)
	delete(m, "a")
	fmt.Println("[func|deleteMap]m=", m)
	delete(m, "c")
	fmt.Println("[func|deleteMap]m=", m)
	fmt.Println()
}

func modifyMap(str string, m map[rune]int) {
	for _, value := range str {
		m[value]++
	}
	fmt.Println("[func|modifyMap]str=", str, "m=", m)
}

func main() {
	declareMap()
	initialMap1()
	initialMap2()
	visitMapKey()
	deleteMap()

	str := "abc"
	m := map[rune]int{}
	fmt.Println("[func|main]str=", str, "m=", m)
	modifyMap(str, m)
	fmt.Println("[func|main]str=", str, "m=", m)
	for key, value := range m {
		fmt.Println("[func|main]key=", key, "value=", value)
	}
}
